<?php
/**
 * @author spenceryg
 * @date 2022/11/25
 * @time 12:38 下午
 * @focus love & life
 */

namespace app\admin\controller\sys\business;

use app\admin\controller\sys\model\AdminAccessModel;
use app\admin\controller\sys\validate\AdminAccessValidate;
use app\common\lib\SpClassMethods;

class AdminAccessBusiness
{
    /**
     * 获取所有公共方法
     * @return array
     * @throws \ReflectionException
     */
    public static function getAllPublicAction(): array
    {
        $res = [];
        $dirName = "../app/admin/controller";
        $handle = @opendir($dirName);
        while (($file = @readdir($handle)) !== false) {
            if (strpos($file, '.php')!==false) {
                $arr = SpClassMethods::getClassPublicMethods(str_replace('.php', '', $file));
                foreach ($arr as $k=>$v) {
                    if (!$k) {
                        $res[] = [
                            'id' => $file,
                            'name' => explode('-', $v['comment'])[0],
                            'pid' => 0
                        ];
                    }
                    $res[] = [
                        'id' => $v['url'],
                        'name' => $v['comment'],
                        'pid' => $file
                    ];
                }
            }
        }
        closedir($handle);
        $dirName = "../app/admin/controller/sys";
        $handle = @opendir($dirName);
        while (($file = @readdir($handle)) !== false) {
            if (strpos($file, '.php')!==false) {
                $file = 'sys/' . $file;
                $arr = SpClassMethods::getClassPublicMethods(str_replace('.php', '', $file));
                foreach ($arr as $k=>$v) {
                    if (!$k) {
                        $res[] = [
                            'id' => $file,
                            'name' => explode('-', $v['comment'])[0],
                            'pid' => 0
                        ];
                    }
                    $res[] = [
                        'id' => $v['url'],
                        'name' => $v['comment'] . ' __ [ '. str_replace('/admin/', '', $v['url']).' ]',
                        'pid' => $file
                    ];
                }
            }
        }
        closedir($handle);
        return $res;
    }

    public static function add($data)
    {
        validate(AdminAccessValidate::class)->check($data);
        $data['path'] = '|' . implode('|', $data['path']) . '|';
        AdminAccessModel::create($data);
    }

    public static function update($data)
    {
        validate(AdminAccessValidate::class)->check($data);
        $data['path'] = '|' . implode('|', $data['path']) . '|';
        AdminAccessModel::update($data);
    }
}
